import { app, BrowserWindow, dialog } from "electron";

const sendLog = (msg)=>{
  const mainWin = BrowserWindow.getAllWindows()  //main
  mainWin.forEach(win=>{
    win.webContents.send('fileWatcher',msg)
  })
}

export const devMenuTemplate = {
  label: "DoKit",
  submenu: [
    {
      label:'Open File',
      accelerator: "CmdOrCtrl+O",
      click: () => {
        const mainWin = BrowserWindow.getFocusedWindow()
        dialog.showOpenDialog(mainWin, { properties: ['openFile'] }, function(path){
          if(path){
            // Start to watch the selected path
            StartWatcher(path[0]);
          }else {
            console.log("No path selected");
          }
        })
      }
    },
    {
      label: "Reload",
      accelerator: "CmdOrCtrl+R",
      click: () => {
        BrowserWindow.getFocusedWindow().webContents.reloadIgnoringCache();
        StartWatcher(false)
      }
    },
    {
      label: "Toggle DevTools",
      accelerator: "Alt+CmdOrCtrl+I",
      click: () => {
        BrowserWindow.getFocusedWindow().toggleDevTools();
      }
    },
    {
      label: "Quit",
      accelerator: "CmdOrCtrl+Q",
      click: () => {
        app.quit();
      }
    }
  ]
};



function StartWatcher(path){
  var chokidar = require("chokidar");
  if(StartWatcher.watcher){
    console.log('close....')
    StartWatcher.watcher.close()
  }
  if(!path){
    console.log('reload..')
    return 
  }
  StartWatcher.watcher = chokidar.watch(path, {
      ignored: /[\/\\]\./,
      persistent: true
  });

  var watcher = StartWatcher.watcher

  function onWatcherReady(){
      console.info('From here can you check for real changes, the initial scan has been completed.');
  }
        
  // Declare the listeners of the watcher
  watcher
  .on('add', function(path) {
        console.log('File', path, 'has been added');
  })
  .on('addDir', function(path) {
        console.log('Directory', path, 'has been added');
  })
  .on('change', function(path) {
      sendLog(`has been changed ==${path}`)
  })
  .on('unlink', function(path) {
       console.log('File', path, 'has been removed');
  })
  .on('unlinkDir', function(path) {
       console.log('Directory', path, 'has been removed');
  })
  .on('error', function(error) {
       console.log('Error happened', error);
  })
  .on('ready', onWatcherReady)
  .on('raw', function(event, path, details) {
       // This event should be triggered everytime something happens.
       console.log('Raw event info:', event, path, details);
  });
}